package syscommand

import (
	"errors"
	"strings"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
)

type MakeCommand struct {
	CmdName string
	BaseCmd
}

func NewMakeCommand() *MakeCommand {
	return &MakeCommand{}
}

func (mc *MakeCommand) Configure() {
	// fmt.Println("MakeCtl -> Configure")
	mc.StringVar(&mc.CmdName, "command", "", "自定义命令类名称，可以指定包名")
}

func (mc *MakeCommand) Execute() error {
	// code ...
	// fmt.Printf("%+v\n", mc)
	if len(mc.CmdName) == 0 {
		return errors.New("自定义命令类名称不能为空")
	}
	path, pkg, command, parseErr := mc.ParsePathAndPkg(mc.CmdName, "command")
	if parseErr != nil {
		return parseErr
	}
	filename := path + helper.CamelString(command, false) + ".go"
	// fmt.Println(filename)

	var cmdTplStr string

	tplFile := enum.ROOT_DIR + "/console/tpl/command.tpl"
	// fmt.Println("tplFile ========== ", tplFile)

	if err, val := helper.ReadFileContent(tplFile, false); err != nil {
		return err
	} else {
		cmdTplStr = val
	}
	// fmt.Println("======= before ======== ", ctlTplStr)

	rootDir := strings.Trim(enum.ROOT_DIR, "/")
	dirs := strings.Split(rootDir, "/")
	// fmt.Println(rootDir)
	// fmt.Printf("=====dirs=========%+v\n", dirs)
	mod := dirs[len(dirs)-1]
	// fmt.Println("=====mod=========", mod, len(dirs))

	baseCmd := mod + "/console/syscommand"
	cmdTplStr = strings.ReplaceAll(cmdTplStr, "{{pkg}}", pkg)
	cmdTplStr = strings.ReplaceAll(cmdTplStr, "{{basaCmd}}", baseCmd)
	cmdTplStr = strings.ReplaceAll(cmdTplStr, "{{commandName}}", command)
	// fmt.Println("========= after ========== ", ctlTplStr)

	if err := helper.WriteToFile(filename, cmdTplStr); err != nil {
		return err
	}

	return nil
}
